/*
 * @Author: xueyp
 * @Date: 2020-06-10 15:39:40
 * @Last Modified by: xueyp
 * @Last Modified time: 2020-06-10 21:13:51
 * @description: 底部操作按钮
 */
<template>
  <div class="buttonGrop">
    <div class="button" v-if="allData.can_start">
      <img src="../../assets/images/btn.png" alt="">
      <div :class="['button-text', onTouch ? 'touch' : '']" @touchstart="() => {onTouch = true}" @touchend="() => {onTouch = false}" @click="goTopunchStart">我要睡啦</div>
    </div>
    <div class="button" v-else-if="allData.can_end">
      <img src="../../assets/images/btn.png" alt="">
      <div :class="['button-text', onTouch ? 'touch' : '']" @touchstart="() => {onTouch = true}" @touchend="() => {onTouch = false}" @click="goTopunchEnd">我起床啦</div>
    </div>
    <div class="button" v-else-if="allData.show_count_down">
      <img src="../../assets/images/grayBtn.png" alt="">
      <div class="button-text noStart"><p style="width: 2.4rem">{{ timeObj && timeObj.hours + ':' + timeObj.minutes + ':' + timeObj.seconds}}</p><p>后开启</p></div>
    </div>
    <div class="button" v-else>
      <img src="../../assets/images/grayBtn.png" alt="">
      <div :class="['button-text', 'btnDisable', onTouch ? 'touch' : '']" @touchstart="() => {onTouch = true}" @touchend="() => {onTouch = false}" @click="showTip">我起床啦</div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import {punchStart, punchEnd, getSleepDetail} from '@/api/request'
import { mapState, mapMutations } from "vuex";

export default {
  data() {
    return {
      endDate: '',
      timeObj:null,
      onTouch: false,
      timer: null
    };
  },
  props: {
    pageData: {
      show_count_down: {
        type: Boolean,
        default: false
      }
    }
  },
  computed: {
    ...mapState({
      allData: 'allData'
    })
  },
  watch: {
    '$store.state.allData' (val) {
      if (val.show_count_down) {
        this.endDate = moment(this.$store.state.serverTime).format('YYYY-MM-DD') + ' ' + this.allData.start_at_hour + ':' + this.allData.start_at_minute + ':00'
        let currentDate = moment(this.$store.state.serverTime, 'YYYY-MM-DD HH:mm:ss');
        this.timeObj = this.calcDate(currentDate, this.endDate);
        this.countDown()
      } else {
        
      }
    }
  },
  mounted () {
    
  },
  methods: {
    ...mapMutations({
      controlPopover: 'CONTROL_POPOVER'
    }),
    showTip() {
      // let status = this.$store.state.popoverShow
      // this.controlPopover({'popoverShow': !status})
      this.$toastMessage({message: '睡眠时间需大于5小时哦', time: 3000})
      
    },
    goTopunchStart () {
      this.dataCollect('TE_MAKEFACES_CLICK', '睡觉赚颜值', {
        ITEM_ID: 1,
        ITEM_NAME: '开启',
        PAGE_ID: 'MakeFaces'
      })
      punchStart({}).then(res => {
        this.$parent.getSleepDetail()
      }).catch(e => {
        this.$toastMessage({message: e.message, time: 3000})
        this.$parent.getSleepDetail()
      })
    },
    goTopunchEnd () {
      this.dataCollect('TE_MAKEFACES_CLICK', '睡觉赚颜值', {
        ITEM_ID: 2,
        ITEM_NAME: '起床',
        PAGE_ID: 'MakeFaces'
      })
      punchEnd({}).then(res => {
        this.$parent.getSleepDetail()
      }).catch(e => {
        this.$toastMessage({message: e.message, time: 3000})
        this.$parent.getSleepDetail()
      })
    },
    buttonText() {
      let timeNow = new Date();
      let hours = timeNow.getHours();
      let text = "";
      if (hours >= 20 || hours <= 2) {
        text = "我要睡啦";
      } else {
        text = "我起床啦";
      }
      return text;
    },
    calcDate(beginDate,endDate){
      let endTime = moment(endDate);
      let beginTime = moment(beginDate);
      const diff = endTime.diff(beginTime);
      const diffDuration = moment.duration(diff);
      if (diff <= 0){
        if (this.$store.state.allData.show_count_down) {
          // this.$parent.getSleepDetail()
        }
      };
      let self = this;
      let days = parseInt(diffDuration.asDays(), 10)
      let hours = parseInt(diffDuration.asHours(), 10)
      let minutes = (parseInt(diffDuration.asMinutes()) % 60)
      let seconds = parseInt(diffDuration.asSeconds()) % 60
      let m = {
          diff:diff,//时间戳
          days: `${days}`,
          hours: `${(hours < 0 || hours >= 24) ? '00' : (hours < 10 ? '0' + hours : hours)}`,
          minutes: `${minutes < 0 ? '00' : minutes < 10 ? '0' + minutes : minutes}`,
          seconds: `${seconds < 0 ? '00' : seconds < 10 ? '0' + seconds : seconds}`,
          toString: function() { 
            return self.isShowDays ? `${this.days} ${this.hours}:${this.minutes}:${this.seconds}` :`${this.hours}:${this.minutes}:${this.seconds}`
          }
      };
      return m;
    },
    formatTime(unix){
      var t = null;
      var d = null;
      var h = null;
      var m = null;
      var s = null;
      //js默认时间戳为毫秒,需要转化成秒
      t = unix / 1000;
      // d = Math.floor(t / (24 * 3600));
      d = Math.floor(t / (24 * 3600));
      h = Math.floor((t-24 * 3600 * d) / 3600);
      m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60);
      s = Math.floor((t - 24 * 3600 * d - h * 3600 - m * 60));

      h = h <10? `0${h}` : `${h}`;
      m = m <10? `0${m}`:`${m}`;
      s = s<10? `0${s}`: `${s}`;
      d = d < 1?`0${d}`:`${d}`;
      return {d,h,m,s}
    },
    countDown(){
      clearInterval(this.timer)
      this.timer = setInterval(()=>{
        this.timeObj.diff-=1000;
        let obj = this.formatTime(this.timeObj.diff)
        this.timeObj.days = obj.d;
        this.timeObj.hours = obj.h;
        this.timeObj.minutes = obj.m;
        this.timeObj.seconds = obj.s;
        if(this.timeObj.diff <=0) {
          this.timeObj = {
            diff: "0",
            days: "00",
            hours: "00",
            minutes: "00",
            seconds: "00"
          }
          clearInterval(this.timer)
          setTimeout(() => {
            this.$parent.getSleepDetail()
          }, 1000)
        }
      },1000)
    }
  }
};
</script>

<style scoped lang="less">
.touch{
  filter: brightness(0.5);
}
.button {
  width: 4.74rem;
  height: 1.38rem;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0.81rem;
  img {
    width: 100%;
    height: 100%;
    box-shadow: 0px 4px 8px 0px rgba(0,0,0,0.3);
    border-radius: 0.69rem;
  }
  .button-text {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    font-size: 0.54rem;
    line-height:1.28rem;
    font-family: Yuanti SC;
    font-weight: bold;
    color: rgba(157, 74, 26, 1);
    text-align: center;
  }
  .btnDisable{
    color: #fff;
  }
  .noStart{
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
